/*
 * THE SOURCE CODES OF THE SOFTWARE ARE VALUABLE ASSETS OF FIDUS TECHNOLOGIES LTD.
 * YOU AGREE TO KEEP ALL SOURCE CODES OF THE SOFTWARE IN CONFIDENCE. YOU MAY NOT TRANSFER
 * OR ASSIGN THE SOFTWARE OR YOUR RIGHTS UNDER THIS AGREEMENT.
 * LIMITED WARRANTY
 * THE SOFTWARE AND ACCOMPANYING WRITTEN MATERIALS (INCLUDING INSTRUCTIONS FOR USE) ARE PROVIDED "AS IS"
 * AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS
 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION)HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
 * IN CONTRACT, STRICT LIABILITY, OR TORT(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
 * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. YOU ASSUME THE ENTIRE
 * RISK AS TO THE RESULTS AND PERFORMANCE OF THE SOFTWARE.
 * FIDUS TECHNOLOGIES DOES NOT WARRANT THAT THE SOFTWARE WILL MEET ALL YOUR REQUIREMENTS, THAT OPERATIONS
 * OF THE SOFTWARE WILL BE UNINTERRUPTED OR ERROR-FREE, OR THAT ALL SOFTWARE ERRORS WILL BE CORRECTED.
 * FIDUS TECHNOLOGIES-SOFTWARE SOLUTIONS IS NOT RESPONSIBLE FOR PROBLEMS CAUSED BY CHANGES IN THE
 * OPERATING CHARACTERISTICS OF COMPUTER HARDWARE OR COMPUTER OPERATING SYSTEMS WHICH ARE MADE AFTER
 * WHICH ARE MADE AFTER THE RELEASE OF THE SOFTWARE NOR FOR PROBLEMS IN THE INTERACTION OF THE SOFTWARE
 * WITH NON-FIDUS TECHNOLOGIES APPLICATION.WILL HAVE NO RESPONSIBILITY TO REPLACE OR REFUND THE LICENSE FEES
 * FOR MEDIA DAMAGED BY ACCIDENT, ABUSE OR MISAPPLICATION. THIS SOFTWARE IS INTENDED FOR COMMERCIAL,
 * INSTITUTIONAL, AND INDUSTRIAL USERS. THE ABOVE WARRANTIES ARE EXCLUSIVE AND IN LIEU OF ALL OTHER WARRANTIES,
 * WHETHER EXPRESSED OR IMPLIED, INCLUDING THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
 * PURPOSE AND NON-INFRINGEMENT. NO ORAL OR WRITTEN INFORMATION OR ADVICE GIVEN BY FIDUS TECHNOLOGIES,
 * ITS EMPLOYEES, DISTRIBUTORS, DEALERS OR AGENTS SHALL INCREASE THE SCOPE OF THE ABOVE WARRANTIES OR
 * CREATE ANY NEW WARRANTIES. NEITHER FIDUS TECHNOLOGIES NOR ANYONE ELSE WHO HAS BEEN INVOLVED IN THE
 * CREATION, PRODUCTION OR DELIVERY OF THE SOFTWARE SHALL BE LIABLE FOR ANY DIRECT, INDIRECT, CONSEQUENTIAL
 * OR INCIDENTAL DAMAGES (INCLUDING DAMAGES FOR LOSS OF BUSINESS PROFITS, BUSINESS LOSSES, BUSINESS
 * INTERRUPTION, LOSS OF DATA, AND THE LIKE) ARISING OUT OF THE USE OR INABILITY TO USE THE SOFTWARE,
 * OR ANY OTHER CLAIM BY ANY PARTY EVEN IF FIDUS TECHNOLOGIES HAS BEEN ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGES. IN THE EVENT FIDUS TECHNOLOGIES IS LIABLE FOR ANY DAMAGES, FIDUS TECHNOLOGIES' LIABILITY
 * FOR DAMAGES SHALL BE LIMITED TO THE AMOUNT PAID FOR THE SOFTWARE UNDER THE TERMS AND CONDITIONS OF THIS
 * AGREEMENT.
 * http://www.fidustechnologies.com
 * Copyright(C) 2010 FIDUS TECHNOLOGIES-Software Solutions(R)
 * All rights reserved.
 */

/*
 * ProductDetailsView.java
 *
 * Created on 2 Sep, 2010, 1:41:44 PM
 */

package com.fidus.inventory.UI.products;

import com.fidus.inventory.beans.products.ProductDetails;
import com.fidus.inventory.beans.products.ProductStock;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.util.List;
import javax.persistence.RollbackException;
import javax.swing.JOptionPane;
import oracle.toplink.essentials.expressions.Expression;
import oracle.toplink.essentials.expressions.ExpressionBuilder;
import org.jdesktop.application.Action;
import org.jdesktop.beansbinding.AbstractBindingListener;
import org.jdesktop.beansbinding.Binding;
import org.jdesktop.beansbinding.PropertyStateEvent;

/**
 *
 * @author Mahesh Kedari<mahesh.kedari@fidustechnologies.com>
 */
public class ProductDetailsView extends javax.swing.JPanel {

    /** Creates new form ProductDetailsView */
    public ProductDetailsView() {
        initComponents();
        entityManager.getTransaction().begin();
        bindingGroup.addBindingListener(new AbstractBindingListener() {
            @Override
            public void targetChanged(Binding binding, PropertyStateEvent event) {
                setSaveNeeded(true);
            }

        });
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        entityManager = java.beans.Beans.isDesignTime() ? null : javax.persistence.Persistence.createEntityManagerFactory("inventorymanagement_dbPU").createEntityManager();
        org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(simple_inventory.Simple_InventoryApp.class).getContext().getResourceMap(ProductDetailsView.class);
        productdetailsQuery = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery(resourceMap.getString("productdetailsQuery.query")); // NOI18N
        productDetailsList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : productdetailsQuery.getResultList();
        productstockQuery = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery(resourceMap.getString("productstockQuery.query")); // NOI18N
        productstockList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(productstockQuery.getResultList());
        productStockQuery = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT p FROM ProductStock p");
        productStockList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : productStockQuery.getResultList();
        measurementUnitConverter1 = new com.fidus.inventory.UI.Items.MeasurementUnitConverter();
        titleLabel = new javax.swing.JLabel();
        jSeparator1 = new javax.swing.JSeparator();
        jToolBar2 = new javax.swing.JToolBar();
        newButton1 = new javax.swing.JButton();
        saveButton1 = new javax.swing.JButton();
        deleteButton1 = new javax.swing.JButton();
        refreshButton = new javax.swing.JButton();
        productCodeLabel = new javax.swing.JLabel();
        productCodeTextField = new javax.swing.JTextField();
        jScrollPane2 = new javax.swing.JScrollPane();
        jXTable1 = new org.jdesktop.swingx.JXTable();
        productNameTextField = new javax.swing.JTextField();
        unitComboBox = new javax.swing.JComboBox();
        jScrollPane1 = new javax.swing.JScrollPane();
        descriptionTextArea = new javax.swing.JTextArea();
        descriptionLabel = new javax.swing.JLabel();
        measureUnitLabel = new javax.swing.JLabel();
        productNameLabel = new javax.swing.JLabel();

        setName("Form"); // NOI18N

        titleLabel.setFont(resourceMap.getFont("titleLabel.font")); // NOI18N
        titleLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        titleLabel.setText(resourceMap.getString("titleLabel.text")); // NOI18N
        titleLabel.setName("titleLabel"); // NOI18N

        jSeparator1.setName("jSeparator1"); // NOI18N

        jToolBar2.setFloatable(false);
        jToolBar2.setRollover(true);
        jToolBar2.setName("jToolBar2"); // NOI18N

        javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(simple_inventory.Simple_InventoryApp.class).getContext().getActionMap(ProductDetailsView.class, this);
        newButton1.setAction(actionMap.get("newRecord")); // NOI18N
        newButton1.setText(resourceMap.getString("newButton1.text")); // NOI18N
        newButton1.setFocusable(false);
        newButton1.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        newButton1.setName("newButton1"); // NOI18N
        newButton1.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jToolBar2.add(newButton1);

        saveButton1.setAction(actionMap.get("save")); // NOI18N
        saveButton1.setText(resourceMap.getString("saveButton1.text")); // NOI18N
        saveButton1.setFocusable(false);
        saveButton1.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        saveButton1.setName("saveButton1"); // NOI18N
        saveButton1.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jToolBar2.add(saveButton1);

        deleteButton1.setAction(actionMap.get("deleteRecord")); // NOI18N
        deleteButton1.setText(resourceMap.getString("deleteButton1.text")); // NOI18N
        deleteButton1.setFocusable(false);
        deleteButton1.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        deleteButton1.setName("deleteButton1"); // NOI18N
        deleteButton1.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jToolBar2.add(deleteButton1);

        refreshButton.setAction(actionMap.get("refreshForm")); // NOI18N
        refreshButton.setText(resourceMap.getString("refreshButton.text")); // NOI18N
        refreshButton.setFocusable(false);
        refreshButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        refreshButton.setName("refreshButton"); // NOI18N
        refreshButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        jToolBar2.add(refreshButton);

        productCodeLabel.setText(resourceMap.getString("productCodeLabel.text")); // NOI18N
        productCodeLabel.setName("productCodeLabel"); // NOI18N

        productCodeTextField.setName("productCodeTextField"); // NOI18N

        org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${product.productCode}"), productCodeTextField, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);
        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${validProduct}"), productCodeTextField, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
        bindingGroup.addBinding(binding);

        jScrollPane2.setName("jScrollPane2"); // NOI18N

        jXTable1.setToolTipText(resourceMap.getString("jXTable1.toolTipText")); // NOI18N
        jXTable1.setColumnSelectionAllowed(true);
        jXTable1.setName("jXTable1"); // NOI18N

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, productStockList, jXTable1);
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${stockQuantity}"));
        columnBinding.setColumnName("Stock Quantity");
        columnBinding.setColumnClass(Float.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${stockCheckedOn}"));
        columnBinding.setColumnName("Stock Checked On");
        columnBinding.setColumnClass(java.util.Date.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${lastSoldQty}"));
        columnBinding.setColumnName("Last Sold Qty");
        columnBinding.setColumnClass(Float.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${salesOrder.orderDate}"));
        columnBinding.setColumnName("Sales Order.order Date");
        columnBinding.setColumnClass(java.util.Date.class);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${validProduct}"), jXTable1, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
        bindingGroup.addBinding(binding);

        jScrollPane2.setViewportView(jXTable1);
        jXTable1.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jXTable1.getColumnModel().getColumn(0).setHeaderValue(resourceMap.getString("jXTable1.columnModel.title0")); // NOI18N
        jXTable1.getColumnModel().getColumn(1).setHeaderValue(resourceMap.getString("jXTable1.columnModel.title1")); // NOI18N
        jXTable1.getColumnModel().getColumn(2).setHeaderValue(resourceMap.getString("jXTable1.columnModel.title2")); // NOI18N
        jXTable1.getColumnModel().getColumn(3).setHeaderValue(resourceMap.getString("jXTable1.columnModel.title3")); // NOI18N

        productNameTextField.setName("productNameTextField"); // NOI18N

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${product.productName}"), productNameTextField, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);
        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${validProduct}"), productNameTextField, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
        bindingGroup.addBinding(binding);

        unitComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "KG", "Ltrs", "milligram", "millileters", "Mtrs.", "CenteMtrs." }));
        unitComboBox.setName("unitComboBox"); // NOI18N

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${product.measurementUnit}"), unitComboBox, org.jdesktop.beansbinding.BeanProperty.create("selectedItem"));
        binding.setConverter(measurementUnitConverter1);
        bindingGroup.addBinding(binding);
        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${validProduct}"), unitComboBox, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
        bindingGroup.addBinding(binding);

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        descriptionTextArea.setColumns(17);
        descriptionTextArea.setRows(2);
        descriptionTextArea.setTabSize(1);
        descriptionTextArea.setName("descriptionTextArea"); // NOI18N

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${product.description}"), descriptionTextArea, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);
        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, this, org.jdesktop.beansbinding.ELProperty.create("${validProduct}"), descriptionTextArea, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
        bindingGroup.addBinding(binding);

        jScrollPane1.setViewportView(descriptionTextArea);

        descriptionLabel.setText(resourceMap.getString("descriptionLabel.text")); // NOI18N
        descriptionLabel.setName("descriptionLabel"); // NOI18N

        measureUnitLabel.setText(resourceMap.getString("measureUnitLabel.text")); // NOI18N
        measureUnitLabel.setName("measureUnitLabel"); // NOI18N

        productNameLabel.setText(resourceMap.getString("productNameLabel.text")); // NOI18N
        productNameLabel.setName("productNameLabel"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, 722, Short.MAX_VALUE)
            .addComponent(titleLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 722, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(productCodeLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 119, Short.MAX_VALUE)
                    .addComponent(productNameLabel)
                    .addComponent(measureUnitLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(descriptionLabel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(jScrollPane1)
                    .addComponent(productNameTextField, javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(productCodeTextField, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 226, Short.MAX_VALUE)
                    .addComponent(unitComboBox, javax.swing.GroupLayout.Alignment.LEADING, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 323, Short.MAX_VALUE)
                .addContainerGap())
            .addComponent(jToolBar2, javax.swing.GroupLayout.DEFAULT_SIZE, 722, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(titleLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 6, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jToolBar2, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(productCodeTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(productCodeLabel))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(productNameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(productNameLabel))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(unitComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(measureUnitLabel))
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(18, 18, 18)
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 127, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(30, 30, 30)
                                .addComponent(descriptionLabel)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 32, Short.MAX_VALUE))
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 294, Short.MAX_VALUE))
                .addContainerGap())
        );

        bindingGroup.bind();
    }// </editor-fold>//GEN-END:initComponents


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton deleteButton1;
    private javax.swing.JLabel descriptionLabel;
    private javax.swing.JTextArea descriptionTextArea;
    private javax.persistence.EntityManager entityManager;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JToolBar jToolBar2;
    private org.jdesktop.swingx.JXTable jXTable1;
    private javax.swing.JLabel measureUnitLabel;
    private com.fidus.inventory.UI.Items.MeasurementUnitConverter measurementUnitConverter1;
    private javax.swing.JButton newButton1;
    private javax.swing.JLabel productCodeLabel;
    private javax.swing.JTextField productCodeTextField;
    private java.util.List<com.fidus.inventory.beans.products.ProductDetails> productDetailsList;
    private javax.swing.JLabel productNameLabel;
    private javax.swing.JTextField productNameTextField;
    private java.util.List<com.fidus.inventory.beans.products.ProductStock> productStockList;
    private javax.persistence.Query productStockQuery;
    private javax.persistence.Query productdetailsQuery;
    private java.util.List<com.fidus.inventory.beans.products.ProductStock> productstockList;
    private javax.persistence.Query productstockQuery;
    private javax.swing.JButton refreshButton;
    private javax.swing.JButton saveButton1;
    private javax.swing.JLabel titleLabel;
    private javax.swing.JComboBox unitComboBox;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables

    //<editor-fold defaultstate="collapsed" desc="Handling product">
    protected boolean validProduct;
    /**
     * This property indicates whether the product property contains a valid
     * ProductDetails object
     */
    public static final String PROP_VALIDPRODUCT = "validProduct";

    /**
     * Get the value of validProduct
     *
     * @return the value of validProduct
     */
    public boolean isValidProduct() {
        return product!=null;
    }

    /**
     * Set the value of validProduct
     *
     * @param validProduct new value of validProduct
     */
    public void setValidProduct(boolean validProduct) {
        boolean oldValidProduct = this.validProduct;
        this.validProduct = validProduct;
        propertyChangeSupport.firePropertyChange(PROP_VALIDPRODUCT, oldValidProduct, validProduct);
    }

    protected ProductDetails product;
    /**
     * This property contains a product under process in this form
     */
    public static final String PROP_PRODUCT = "product";

    /**
     * Get the value of product
     *
     * @return the value of product
     */
    public ProductDetails getProduct() {
        return product;
    }

    /**
     * Set the value of product
     *
     * @param product new value of product
     */
    public void setProduct(ProductDetails product) {
        ProductDetails oldProduct = this.product;
        this.product = product;
        propertyChangeSupport.firePropertyChange(PROP_PRODUCT, oldProduct, product);
        
        /* Inform entityManager about change in selected product */
        if(product.getProductID()==null){
            /* if the product is new, persist it with Entity Manager */
            entityManager.persist(this.product);
        }else{
            /* if its an existing product, merge it into list and load its
             * product list
             */
            entityManager.merge(this.product);
            loadProductStock();
        }
        setValidProduct(true);
    }
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc="Load the stock data into table">
    /*
     * This function will load the stock of current selected product into 
     * product table
     */
    private void loadProductStock(){
        /*   Remove All the records from stock table */
        productstockList.removeAll(productstockList);

        /*
         * Create Expression for fetching the product stock for current selected
         * Product
         */
        ExpressionBuilder expressionBuilder = new ExpressionBuilder(ProductStock.class);
        Expression expression = expressionBuilder.get("productDetails").equal(product);
        
        /* Execute the query and get result into temporary list - stockList */
        List<ProductStock> stockList = ((oracle.toplink.essentials.ejb.cmp3.EntityManager)
                entityManager.getDelegate()).createQuery(expression, ProductStock.class).getResultList();

        /*
         * Check if the stockList is empty. if not then load the list to productstockList
         * Please note the due to binding, data will automatically get loaded to
         * productTable. Also note that the productstockList should be made
         * observable as the data is going to get changed runtime. 
         */
        
        if (!stockList.isEmpty()) {
            productstockList.addAll(stockList);
        }
    }
    //</editor-fold>
    
    //<editor-fold defaultstate="collapsed" desc="Handle Tool bar actions">
    /**
     * This action will add new product
     */
    @Action
    public void newRecord(){
        ProductDetails productDetails = new ProductDetails();
        productDetailsList.add(productDetails);
        setProduct(productDetails);
        setSaveNeeded(true);
    }
    
        @Action(enabledProperty="validProduct")
    public void deleteRecord(){
        try{
            productDetailsList.remove(product);
            entityManager.remove(product);
            setSaveNeeded(true);
        }catch(Exception ex){
            JOptionPane.showMessageDialog(null, "Failed to delete record", "Product Details", JOptionPane.ERROR_MESSAGE);
        }
    }

    /*
     * Define a boolean variable saveNeeded to enable the save button only when
     * the data in form gets changed.
     */
    protected boolean saveNeeded;
    public static final String PROP_SAVENEEDED = "saveNeeded";

    /**
     * Get the value of saveNeeded
     *
     * @return the value of saveNeeded
     */
    public boolean isSaveNeeded() {
        return saveNeeded;
    }

    /**
     * Set the value of saveNeeded
     *
     * @param saveNeeded new value of saveNeeded
     */
    public void setSaveNeeded(boolean saveNeeded) {
        boolean oldSaveNeeded = this.saveNeeded;
        this.saveNeeded = saveNeeded;
        propertyChangeSupport.firePropertyChange(PROP_SAVENEEDED, oldSaveNeeded,
                saveNeeded);
    }
    
    /**
     * Save functionality for saving the record.
     */
        @Action(enabledProperty="saveNeeded")
    public void save(){
        try{
            entityManager.getTransaction().commit();
            JOptionPane.showMessageDialog(null, "Record Saved Successfully", 
                    "Product Details", WIDTH);
            setSaveNeeded(false);
        }catch(RollbackException ex){
            /* Exception has occured while saving the record. */
            JOptionPane.showMessageDialog(null, "Failed to save records",
                    "Product Details", JOptionPane.ERROR_MESSAGE);
        }finally{
            if(!entityManager.getTransaction().isActive()){
                entityManager.getTransaction().begin();
            }
        }
    }
    /**
     * This action will Refresh the form data
     */
        @Action(enabledProperty="validProduct")
    public void refreshForm(){
        //TODO refresh product details
    }

    /**
     * This action will print product details
     */
    @Action(enabledProperty=PROP_VALIDPRODUCT)
    public void printProduct(){
        //TODO print product details
    }
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc="Property Change Support">
    private PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this);

    /**
     * Add PropertyChangeListener.
     *
     * @param listener
     */
    @Override
    public void addPropertyChangeListener(PropertyChangeListener listener) {
        propertyChangeSupport.addPropertyChangeListener(listener);
    }

    /**
     * Remove PropertyChangeListener.
     *
     * @param listener
     */
    @Override
    public void removePropertyChangeListener(PropertyChangeListener listener) {
        propertyChangeSupport.removePropertyChangeListener(listener);
    }
    //</editor-fold>

}
